package com.atguigu.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.client.CartFeignClient;
import com.atguigu.client.ProductFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.enums.OrderStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.executor.MyExecutor;
import com.atguigu.mapper.OrderInfoMapper;
import com.atguigu.service.OrderDetailService;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.HttpClientUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 订单表 订单表 服务实现类
 * </p>
 *
 * @author yangchaolove
 * @since 2022-03-04
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private ProductFeignClient productFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${cancel.order.delay}")
    private Integer cancelOrderDelay;
    @Override
    public String generateTradeNo(String userId) {
        String tradeNo = UUID.randomUUID().toString();
        //把流水号放到redis中
        String tradeNoKey = "user:" + userId + ":tradeNo";
        redisTemplate.opsForValue().set(tradeNoKey, tradeNo);
        return tradeNo;
    }

    @Override
    public Long saveOrderAndDetail(OrderInfo orderInfo) {
        //a.保存订单基本信息
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        //商品对外订单号
        String outTradeNo="yangchao-"+System.currentTimeMillis()+""+new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        //订单主体信息
        orderInfo.setTradeBody("我的购物商品");
        orderInfo.setCreateTime(new Date());
        //设置订单支付过期时间 设置30分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,cancelOrderDelay);
        orderInfo.setExpireTime(calendar.getTime());
        //订单进程状态
        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        //商品的总价格
        orderInfo.setTotalMoney(new BigDecimal("0.01"));
        baseMapper.insert(orderInfo);
        //b.保存订单详情信息
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            //该商品详情属于哪个订单
            orderDetail.setOrderId(orderInfo.getId());
        }
        orderDetailService.saveBatch(orderDetailList);

        //发送一个延迟消息 定时取消订单
        rabbitTemplate.convertAndSend(
                MqConst.CANCEL_ORDER_EXCHANGE,
                MqConst.CANCEL_ORDER_ROUTE_KEY,
                orderInfo.getId(),
                correlationData->{
                    correlationData.getMessageProperties().setDelay(cancelOrderDelay);
                    return correlationData;
                });
        return orderInfo.getId();
    }

    @Override
    public boolean checkTradeNo(String tradeNo, String userId) {
        String tradeNoKey="user:"+userId+":tradeNo";
        String redisTradeNo = (String)redisTemplate.opsForValue().get(tradeNoKey);
        return tradeNo.equals(redisTradeNo);
    }

    @Override
    public void deleteTradeNo(String userId) {
        String tradeNoKey="user:"+userId+":tradeNo";
        redisTemplate.delete(tradeNoKey);
    }

    @Override
    public List<String> checkStockAndPrice(String userId, OrderInfo orderInfo) {
        //新建一个list用于保存警告信息
        List<String> warningInfoList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //异步编排的集合
        List<CompletableFuture> mulitFutureList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                //看每个商品库存是否足够 调用接口
                //http://localhost:8100/hasStock?skuId=24&num=99
                Long skuId = orderDetail.getSkuId();
                String skuNum = orderDetail.getSkuNum();

                CompletableFuture<Void> checkStockFuture = CompletableFuture.runAsync(() -> {
                    String result = HttpClientUtil.doGet("http://localhost:8100/hasStock?skuId=" + skuId + "&num=" + skuNum);
                    //0:无库存   1:有库存
                    if ("0".equals(result)) {
                        warningInfoList.add(orderDetail.getSkuName() + "库存不足!");
                    }
                }, MyExecutor.getInstance());
                mulitFutureList.add(checkStockFuture);


                CompletableFuture<Void> checkPricekFuture = CompletableFuture.runAsync(() -> {
                    //验证价格是否是最新价格
                    BigDecimal realTimePrice = productFeignClient.getSkuPrice(skuId);
                    //判断当前送货清单里面的商品价格与实时价格
                    if(orderDetail.getOrderPrice().compareTo(realTimePrice)!=0){
                        warningInfoList.add(orderDetail.getSkuName()+"价格有变化!");
                        //更新缓存里面的价格信息
                        cartFeignClient.queryFromDbToRedis(userId);
                    }
                }, MyExecutor.getInstance());
                mulitFutureList.add(checkPricekFuture);
            }
        }
        //需要两个同时昨晚才能往下走
        CompletableFuture[] mulitFutureArray= new CompletableFuture[mulitFutureList.size()];
        CompletableFuture.allOf(mulitFutureList.toArray(mulitFutureArray)).join();
        return warningInfoList;
    }

    @Override
    public void updateOrderStatus(OrderInfo orderInfo, ProcessStatus processStatus) {
        //修改订单状态
        orderInfo.setOrderStatus(processStatus.getOrderStatus().name());
        orderInfo.setProcessStatus(processStatus.name());
        baseMapper.updateById(orderInfo);
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //拿取订单详情信息
        if(orderInfo!=null){
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
            orderInfo.setOrderDetailList(orderDetailList);
        }
        return orderInfo;
    }

    @Override
    public void sendMsgToWareHouse(OrderInfo orderInfo) {
        //将订单修改为已通知仓库的状态
        updateOrderStatus(orderInfo,ProcessStatus.NOTIFIED_WARE);
        //拼接传递消息参数json数据
        Map<String, Object> dataMap = assembleWareHouseData(orderInfo);
        String jsonData = JSON.toJSONString(dataMap);
        //发送消息给仓库系统
        rabbitTemplate.convertAndSend(MqConst.DECREASE_STOCK_EXCHANGE,MqConst.DECREASE_STOCK_ROUTE_KEY,jsonData);
    }

    @Override
    public String splitOrder(Long orderId, String wareHouseIdSkuIdMapJson) {
        //24,18,30
        //[{"wareHouseId":"1","skuIdList":["24"]},{"wareHouseId":"2","skuIdList":["30"]}]
        //a.获取原始订单
        OrderInfo originalOrder = getOrderInfo(orderId);
        //b.设置 子订单信息
        List<Map> wareHouseIdSkuIdMapList = JSON.parseArray(wareHouseIdSkuIdMapJson, Map.class);

        List<Map> childOrderInfoMapList = new ArrayList<>();
        for (Map wareHouseIdSkuIdMap : wareHouseIdSkuIdMapList) {
            String wareHouseId=(String)wareHouseIdSkuIdMap.get("wareHouseId");
            List<String> skuIdList=(List<String>)wareHouseIdSkuIdMap.get("skuIdList");
            //子订单的基本信息
            OrderInfo childOrderInfo = new OrderInfo();
            //以下操作有点累
            //childOrderInfo.setConsignee(originalOrder.getConsignee());
            //childOrderInfo.setConsigneeTel(originalOrder.getConsigneeTel());
            BeanUtils.copyProperties(originalOrder,childOrderInfo);
            //设置子订单仓库id
            childOrderInfo.setWareHouseId(wareHouseId);
            //设置子订单的父id为orderId
            childOrderInfo.setParentOrderId(orderId);
            childOrderInfo.setId(null);
            //设置子订单的详情信息
            List<OrderDetail> originalOrderDetailList = originalOrder.getOrderDetailList();
            //c.设置子订单详情信息
            List<OrderDetail> childOrderDetailList=new ArrayList<>();
            BigDecimal totalMoney = new BigDecimal(0);
            for (OrderDetail originalOrderDetail : originalOrderDetailList) {
                for (String skuId : skuIdList) {
                    if(originalOrderDetail.getSkuId()==Long.parseLong(skuId)){
                        childOrderDetailList.add(originalOrderDetail);
                        //设置子订单总金额
                        BigDecimal orderPrice = originalOrderDetail.getOrderPrice();
                        String skuNum = originalOrderDetail.getSkuNum();
                        totalMoney=totalMoney.add(orderPrice.multiply(new BigDecimal(skuNum)));
                    }
                }
            }
            //设置子订单基本信息的订单详情信息
            childOrderInfo.setOrderDetailList(childOrderDetailList);
            //设置子订单的总价
            childOrderInfo.setTotalMoney(totalMoney);
            //d.保存子订单
            saveOrderAndDetail(childOrderInfo);
            //把子订单转换为json字符串
            Map<String, Object> dataMap = assembleWareHouseData(childOrderInfo);
            childOrderInfoMapList.add(dataMap);
        }
        //e.修改原始订单状态
        updateOrderStatus(originalOrder,ProcessStatus.SPLIT);
        //f.返回数据给库存系统
        return JSON.toJSONString(childOrderInfoMapList);

    }

    private Map<String, Object> assembleWareHouseData(OrderInfo orderInfo) {
        //先构造一个map
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderId",orderInfo.getId());
        dataMap.put("consignee",orderInfo.getConsignee());
        dataMap.put("consigneeTel",orderInfo.getConsigneeTel());
        dataMap.put("orderComment",orderInfo.getOrderComment());
        dataMap.put("orderBody",orderInfo.getTradeBody());
        dataMap.put("deliveryAddress",orderInfo.getDeliveryAddress());
        dataMap.put("paymentWay",2);
        //TODO 这里要添加一个非常重要的字段   拆单字段
        dataMap.put("wareId",orderInfo.getWareHouseId());
        //商品清单
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //把商品清单放入一个list集合里面
        List<Map> orderDetailMapList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            Map<String, Object> orderDetailMap = new HashMap<>();
            orderDetailMap.put("skuId",orderDetail.getSkuId());
            orderDetailMap.put("skuNum",orderDetail.getSkuNum());
            orderDetailMap.put("skuName",orderDetail.getSkuName());
            orderDetailMapList.add(orderDetailMap);
        }
        dataMap.put("details",orderDetailMapList);
        return dataMap;
    }

    


}
